package wodegua.d23_test.demo6;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MyLinkedList<E> {
    public Node<E> add(){
        Node<E> head = null;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入节点值");
            String data = scanner.next();
            if (head == null) {
                head = new Node(data, null);
            } else {
                Node<E> temp = head;
                while (temp.next != null) {
                    temp = temp.next;
                }
                temp.next = new Node(data, null);
            }
            if (data.equals("exit")) {
                return head;
            }
        }
    }

    /**
     * 反转
     * 1 2 3 4 5
     * 1 4 3 2 5
     */
    public Node<E> reverse(Node<E> head, int left, int right){
        if (head == null || head.next == null || left < 0 || left >= right) {
            return head;
        }
        int index = 0;
        Node<E> rs = head;
        Node<E> mark = head;
        List<E> list = new ArrayList<>();
        while (head != null) {
            index++;
            if (index == left) {
                mark = head;
            }
            if (index >= left && index <= right) {
                list.add(head.data);
            }
            if (index == right) {
                break;
            }
            head = head.next;
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            E e = list.get(i);
            mark.data = e;
            mark = mark.next;
        }
        return rs;
    }

    public void forEach(Node<E> head){
        if (head == null) {
            System.out.println("null");
        }
        while (head != null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
    }
}
